package com.xh3140.android.widget.utils;

import android.content.Context;

import androidx.annotation.NonNull;

import java.lang.reflect.Array;

@SuppressWarnings("unused")
public final class DimenUtils {
    /**
     * 禁止实例化
     */
    private DimenUtils() {
        throw new AssertionError("This class prohibits instantiation.");
    }

    public static int dp2px(@NonNull Context context, float dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density + 0.5f);
    }

    public static int sp2px(@NonNull Context context, float sp) {
        return (int) (sp * context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
    }

    public static float px2dp(@NonNull Context context, int px) {
        return px / context.getResources().getDisplayMetrics().density;
    }

    public static float px2sp(@NonNull Context context, int px) {
        return px / context.getResources().getDisplayMetrics().scaledDensity;
    }

    public static int[] dps2pxs(@NonNull Context context, float... dps) {
        if (dps == null || dps.length == 0) {
            return new int[]{};
        }
        final float density = context.getResources().getDisplayMetrics().density;
        final int[] pxs = (int[]) Array.newInstance(int.class, dps.length);
        for (int i = 0; i < pxs.length; ++i) {
            pxs[i] = (int) (dps[i] * density + 0.5f);
        }
        return pxs;
    }

    public static float[] pxs2dps(@NonNull Context context, int... pxs) {
        if (pxs == null || pxs.length == 0) {
            return new float[]{};
        }
        final float density = context.getResources().getDisplayMetrics().density;
        final float[] dps = (float[]) Array.newInstance(float.class, pxs.length);
        for (int i = 0; i < pxs.length; ++i) {
            dps[i] = pxs[i] / density;
        }
        return dps;
    }

    public static int screenWidth(@NonNull Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int screenHeight(@NonNull Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }
}
